<!DOCTYPE html>
<html>
<head>
  <meta charset="utf-8">
  

  
  <title>JDBC的简单使用——MySQL | 海晨忆的博客</title>
  <meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1">
  
  
  
  <meta name="description" content="&amp;emsp;&amp;emsp;前面几篇学了基本的SQL语句和用工具操作数据库，今天讲一下用代码操作数据库。 连接MySQL&amp;emsp;&amp;emsp;首先记得需要导包，jdbc连接MySQL数据库的jar包，名字：mysql-connector-java &amp;emsp;&amp;emsp;首先记得需要导包，jdbc连接MySQL数据库的jar包，名字：mysql-connector-java &amp;emsp;&amp;emsp;">
<meta property="og:type" content="article">
<meta property="og:title" content="JDBC的简单使用——MySQL">
<meta property="og:url" content="https://haichenyi.com/2018/10/11/JDBC的简单使用——MySQL/index.html">
<meta property="og:site_name" content="海晨忆的博客">
<meta property="og:description" content="&amp;emsp;&amp;emsp;前面几篇学了基本的SQL语句和用工具操作数据库，今天讲一下用代码操作数据库。 连接MySQL&amp;emsp;&amp;emsp;首先记得需要导包，jdbc连接MySQL数据库的jar包，名字：mysql-connector-java &amp;emsp;&amp;emsp;首先记得需要导包，jdbc连接MySQL数据库的jar包，名字：mysql-connector-java &amp;emsp;&amp;emsp;">
<meta property="og:locale" content="zh-Hans">
<meta property="og:updated_time" content="2018-10-11T15:03:08.367Z">
<meta name="twitter:card" content="summary">
<meta name="twitter:title" content="JDBC的简单使用——MySQL">
<meta name="twitter:description" content="&amp;emsp;&amp;emsp;前面几篇学了基本的SQL语句和用工具操作数据库，今天讲一下用代码操作数据库。 连接MySQL&amp;emsp;&amp;emsp;首先记得需要导包，jdbc连接MySQL数据库的jar包，名字：mysql-connector-java &amp;emsp;&amp;emsp;首先记得需要导包，jdbc连接MySQL数据库的jar包，名字：mysql-connector-java &amp;emsp;&amp;emsp;">
  
    <link rel="alternate" href="/atom.xml" title="海晨忆的博客" type="application/atom+xml">
  
  
    <link rel="icon" href="/uploads/artistic_image/head.jpg">
  
  
    <link href="//fonts.googleapis.com/css?family=Source+Code+Pro" rel="stylesheet" type="text/css">
  
  <link rel="stylesheet" href="/css/style.css">
  <link rel="stylesheet" href="/css/highlight.css">
  <script>
  let antiquityStorage = window.sessionStorage.getItem('antiquitySessionStorage');
  if (antiquityStorage == '' || antiquityStorage == null) {
    var antiquityLoader = '<div id="loaderbox"><div class="loader"><div class="load-roll"><div class="load-top"></div><div class="load-right"></div><div class="load-bottom"></div></div></div></div>';
    document.write(antiquityLoader);
    document.body.style.overflow = 'hidden'
  }
  </script>
</head>

<body>
  <div id="fullpage" class="mobile-nav-right">
    
      <div id="wrapper" style="background-image: url(/uploads/artistic_image/bg.jpg)" title="背景图片来自网络">
    
    
      <header id="header">
  <div id="nav-toggle" class="nav-toggle"></div>
  <div class="head-box global-width">
    <nav class="nav-box nav-right">
      
        <a class="nav-item" href="/" title
        
        >首页</a>
      
        <a class="nav-item" href="/archives" title
        
        >归档</a>
      
        <a class="nav-item" href="/about" title
        
        >简历</a>
      
    </nav>
  </div>
</header>
      <div id="middlecontent" title class="global-width sidebar-left">
        <section id="main"><article id="post-JDBC的简单使用——MySQL" class="article global-container article-type-post" itemscope itemprop="blogPost">
  
    <header class="article-header">
      
  
    <h1 class="article-title" itemprop="name">
      JDBC的简单使用——MySQL
    </h1>
  

    </header>
  
  <div class="article-meta">
    <a href="/2018/10/11/JDBC的简单使用——MySQL/" class="article-date">
  <time datetime="2018-10-11T14:51:00.000Z" itemprop="datePublished">2018-10-11</time>
</a>
    
  <div class="article-category">
    <a class="article-category-link" href="/categories/数据库-JDBC/">数据库 -JDBC</a>
  </div>

    
  </div>
  
    <span id="busuanzi_container_page_pv">
      本文总阅读量<span id="busuanzi_value_page_pv"></span>次
    </span>
  

  <div class="article-inner">
    
    <div class="article-content article-content-cloud doorframe mac" itemprop="articleBody">
      
        <p>&emsp;&emsp;前面几篇学了基本的SQL语句和用工具操作数据库，今天讲一下用代码操作数据库。</p>
<h4 id="连接MySQL"><a href="#连接MySQL" class="headerlink" title="连接MySQL"></a>连接MySQL</h4><p>&emsp;&emsp;<strong><em>首先记得需要导包，jdbc连接MySQL数据库的jar包，名字：mysql-connector-java</em></strong></p>
<p>&emsp;&emsp;<strong><em>首先记得需要导包，jdbc连接MySQL数据库的jar包，名字：mysql-connector-java</em></strong></p>
<p>&emsp;&emsp;<strong><em>首先记得需要导包，jdbc连接MySQL数据库的jar包，名字：mysql-connector-java</em></strong></p>
<a id="more"></a>
<p>代码如下：</p>
<div class="highlight-box"autocomplete="off" autocorrect="off" autocapitalize="off" spellcheck="false" contenteditable="true"data-rel="PLAIN"><figure class="iseeu highlight /plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br></pre></td><td class="code"><pre><span class="line">//1、获取驱动类,路动类路径：com.mysql.jdbc.Driver</span><br><span class="line">Class.forName(&quot;com.mysql.jdbc.Driver&quot;);</span><br><span class="line">//获取url：jdbc:mysql://ip:端口号/数据库名称</span><br><span class="line">String url = &quot;jdbc:mysql://localhost:3306/test4&quot;;</span><br><span class="line">//用户名</span><br><span class="line">String username = &quot;root&quot;;</span><br><span class="line">//密码</span><br><span class="line">String password = &quot;123&quot;;</span><br><span class="line">//获取Connection对象</span><br><span class="line">Connection connection = DriverManager.getConnection(url, username, password);</span><br><span class="line">System.out.print(connection);</span><br></pre></td></tr></table></figure></div>
<p>&emsp;&emsp;总的来说，先要获取驱动类，然后就是获取Connection对象，就是一行代码<code>DriverManager.getConnection(url, username, password);</code>能走通，就说明连接上了。</p>
<h4 id="修改数据库"><a href="#修改数据库" class="headerlink" title="修改数据库"></a>修改数据库</h4><div class="highlight-box"autocomplete="off" autocorrect="off" autocapitalize="off" spellcheck="false" contenteditable="true"data-rel="PLAIN"><figure class="iseeu highlight /plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br></pre></td><td class="code"><pre><span class="line">@Test</span><br><span class="line">    public void test1() throws ClassNotFoundException, SQLException &#123;</span><br><span class="line">        //获取驱动类</span><br><span class="line">        Class.forName(&quot;com.mysql.jdbc.Driver&quot;);</span><br><span class="line">        //获取url</span><br><span class="line">        String url = &quot;jdbc:mysql://localhost:3306/test4&quot;;</span><br><span class="line">        //用户名</span><br><span class="line">        String username = &quot;root&quot;;</span><br><span class="line">        //密码</span><br><span class="line">        String password = &quot;123&quot;;</span><br><span class="line">        //获取Connection对象</span><br><span class="line">        Connection connection = DriverManager.getConnection(url, username, password);</span><br><span class="line">        System.out.print(connection);</span><br><span class="line">        //获取Statement对象</span><br><span class="line">        Statement statement = connection.createStatement();</span><br><span class="line">        //String sql=&quot;INSERT INTO employee (eid,ename,edid) VALUES(null,&apos;小红&apos;,2)&quot;;</span><br><span class="line">        String sql = &quot;UPDATE employee SET edid=1 WHERE ename=&apos;小红&apos;&quot;;</span><br><span class="line">        statement.executeUpdate(sql);</span><br><span class="line">        statement.close();</span><br><span class="line">        connection.close();</span><br><span class="line">    &#125;</span><br></pre></td></tr></table></figure></div>
<p>&emsp;&emsp;就是在连接数据库之后，通过Connection对象获取Statement对象，通过Statement对象的execute方法执行对应的SQL语句，最后记得关闭</p>
<h4 id="查询数据库"><a href="#查询数据库" class="headerlink" title="查询数据库"></a>查询数据库</h4><div class="highlight-box"autocomplete="off" autocorrect="off" autocapitalize="off" spellcheck="false" contenteditable="true"data-rel="PLAIN"><figure class="iseeu highlight /plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br></pre></td><td class="code"><pre><span class="line">@Test</span><br><span class="line">    public void test3() &#123;</span><br><span class="line">        Connection con = null;</span><br><span class="line">        Statement state = null;</span><br><span class="line">        ResultSet resultSet = null;</span><br><span class="line">        try &#123;</span><br><span class="line">            String driverClassName = &quot;com.mysql.jdbc.Driver&quot;;</span><br><span class="line">            String url = &quot;jdbc:mysql://localhost:3306/test4&quot;;</span><br><span class="line">            String username = &quot;root&quot;;</span><br><span class="line">            String password = &quot;123&quot;;</span><br><span class="line">            Class.forName(driverClassName);</span><br><span class="line">            con = DriverManager.getConnection(url, username, password);</span><br><span class="line">            state = con.createStatement();</span><br><span class="line">            String querySQL = &quot;SELECT * FROM employee&quot;;</span><br><span class="line">            resultSet = state.executeQuery(querySQL);</span><br><span class="line">            List&lt;Map&lt;String, String&gt;&gt; mapList = new ArrayList&lt;&gt;();</span><br><span class="line">            while (resultSet.next()) &#123;</span><br><span class="line">                Map&lt;String, String&gt; map = new HashMap&lt;&gt;();</span><br><span class="line">                map.put(&quot;ename&quot;, resultSet.getString(&quot;ename&quot;));</span><br><span class="line">                map.put(&quot;edid&quot;, String.valueOf(resultSet.getInt(&quot;edid&quot;)));</span><br><span class="line">                mapList.add(map);</span><br><span class="line">            &#125;</span><br><span class="line">            System.out.print(mapList.size());</span><br><span class="line">        &#125; catch (Exception e) &#123;</span><br><span class="line">            throw new RuntimeException(e);</span><br><span class="line">        &#125; finally &#123;</span><br><span class="line">            try &#123;</span><br><span class="line">                if (resultSet != null) &#123;</span><br><span class="line">                    resultSet.close();</span><br><span class="line">                &#125;</span><br><span class="line">                if (state != null) &#123;</span><br><span class="line">                    state.close();</span><br><span class="line">                &#125;</span><br><span class="line">                if (con != null) &#123;</span><br><span class="line">                    con.close();</span><br><span class="line">                &#125;</span><br><span class="line">            &#125; catch (Exception e) &#123;</span><br><span class="line">                e.printStackTrace();</span><br><span class="line">            &#125;</span><br><span class="line">        &#125;</span><br><span class="line">    &#125;</span><br></pre></td></tr></table></figure></div>
<p>&emsp;&emsp;查询数据库需要注意的地方就是：</p>
<ol>
<li><p>执行SQL语句的方法是<code>executeQuery()</code>，只能执行查询语句。</p>
</li>
<li><p>他有一个返回值ResultSet，然后循环这个Set对象，获取数据，他提供了一个移动光标的方法<code>next()</code>，当他为null的时候，返回false，结束循环。</p>
</li>
<li><p>还提供了一系列的get方法，传表每一栏的下标index，或者每一栏的名称，获取对应的值。值的类型要与get的类型相同。值为int，就用getInt，值为String就用getString</p>
</li>
<li><p>最后记得关闭连接，倒着关闭。</p>
</li>
</ol>
<h4 id="PreparedStatement"><a href="#PreparedStatement" class="headerlink" title="PreparedStatement"></a>PreparedStatement</h4><p>&emsp;&emsp;上面用自己拼接sql语句的方式查询数据库，会容易被sql攻击。所以，我们需要用<code>PreparedStatement</code>来防止被sql攻击，具体方式如下：</p>
<div class="highlight-box"autocomplete="off" autocorrect="off" autocapitalize="off" spellcheck="false" contenteditable="true"data-rel="PLAIN"><figure class="iseeu highlight /plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br></pre></td><td class="code"><pre><span class="line">public boolean login(String username, String password) throws Exception &#123;</span><br><span class="line">        Connection connection = null;</span><br><span class="line">        PreparedStatement pstat = null;</span><br><span class="line">        ResultSet rs = null;</span><br><span class="line">        try &#123;</span><br><span class="line">            Class.forName(&quot;com.mysql.jdbc.Driver&quot;);</span><br><span class="line">            String url = &quot;jdbc:mysql://localhost:3306/test4&quot;;</span><br><span class="line">            String user = &quot;root&quot;;</span><br><span class="line">            String psw = &quot;123&quot;;</span><br><span class="line">            connection = DriverManager.getConnection(url, user, psw);</span><br><span class="line">            String sql = &quot;select * from t_user where username=? and psw=?&quot;;</span><br><span class="line">            pstat = connection.prepareStatement(sql);</span><br><span class="line">            pstat.setString(1, username);</span><br><span class="line">            pstat.setString(2, password);</span><br><span class="line">            rs = pstat.executeQuery();</span><br><span class="line">            return rs.next();</span><br><span class="line">        &#125; catch (Exception e) &#123;</span><br><span class="line">            throw new RuntimeException(e);</span><br><span class="line">        &#125; finally &#123;</span><br><span class="line">            if (rs != null) rs.close();</span><br><span class="line">            if (pstat != null) pstat.close();</span><br><span class="line">            if (connection != null) connection.close();</span><br><span class="line">        &#125;</span><br><span class="line">    &#125;</span><br></pre></td></tr></table></figure></div>
<p>&emsp;&emsp;如上，是一个登录接口，传用户名，密码给后台，后台查询数据库，我们在获取了connection之后，通过connection调用prepareStatement方法，需要传一个sql模板。</p>
<div class="highlight-box"autocomplete="off" autocorrect="off" autocapitalize="off" spellcheck="false" contenteditable="true"data-rel="PLAIN"><figure class="iseeu highlight /plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">String sql = &quot;select * from t_user where username=? and psw=?&quot;;</span><br></pre></td></tr></table></figure></div>
<p>&emsp;&emsp;什么是sql模板呢？就是吧需要动态传的参数用问好代替。我们上面这个查询语句，需要动态变化的就是username和psw。然后，我们调用PreparedStatement的setXxx方法，去设置值，第一个参数表示给第几个值赋值，第二个参数就是需要赋值的值</p>
<div class="highlight-box"autocomplete="off" autocorrect="off" autocapitalize="off" spellcheck="false" contenteditable="true"data-rel="PLAIN"><figure class="iseeu highlight /plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br></pre></td><td class="code"><pre><span class="line">//给第一个参数赋值为username</span><br><span class="line">pstat.setString(1, username);</span><br><span class="line">//给第二个参数赋值为password</span><br><span class="line">pstat.setString(2, password);</span><br></pre></td></tr></table></figure></div>
<h4 id="大数据存储"><a href="#大数据存储" class="headerlink" title="大数据存储"></a>大数据存储</h4><p>&emsp;&emsp;这里以存mp3为例</p>
<div class="highlight-box"autocomplete="off" autocorrect="off" autocapitalize="off" spellcheck="false" contenteditable="true"data-rel="PLAIN"><figure class="iseeu highlight /plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br></pre></td><td class="code"><pre><span class="line">CREATE TABLE t_binary(</span><br><span class="line">	id INT PRIMARY KEY AUTO_INCREMENT,</span><br><span class="line">	NAME VARCHAR(50),</span><br><span class="line">	DATA MEDIUMBLOB</span><br><span class="line">)</span><br></pre></td></tr></table></figure></div>
<p>&emsp;&emsp;如上，首先创建一张表去存数据，数据类型不要错了，BLOB类型。</p>
<div class="highlight-box"autocomplete="off" autocorrect="off" autocapitalize="off" spellcheck="false" contenteditable="true"data-rel="PLAIN"><figure class="iseeu highlight /plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br></pre></td><td class="code"><pre><span class="line">@Test</span><br><span class="line">    public void test1() throws SQLException, IOException &#123;</span><br><span class="line">        Connection connection = JDBCUtils.getConnection();</span><br><span class="line">        String sql=&quot;INSERT INTO t_binary VALUE(?,?,?)&quot;;</span><br><span class="line">        PreparedStatement pstat = connection.prepareStatement(sql);</span><br><span class="line">        pstat.setInt(1,1);</span><br><span class="line">        pstat.setString(2,&quot;KenT - 唱给谁听.mp3&quot;);</span><br><span class="line">        byte[] bytes= IOUtils.toByteArray(new FileInputStream(&quot;D:/CloudMusic/KenT - 唱给谁听.mp3&quot;));</span><br><span class="line">        Blob blob=new SerialBlob(bytes);</span><br><span class="line">        pstat.setBlob(3,blob);</span><br><span class="line">        pstat.executeLargeUpdate();</span><br><span class="line">    &#125;</span><br></pre></td></tr></table></figure></div>
<p>&emsp;&emsp;上面test1就是存的方法，步骤：</p>
<ol>
<li><p>先连接数据库，获取Connection对象</p>
</li>
<li><p>然后，获取PreparedStatement对象，设置参数，其中blob参数，Blob是一个接口，先获取他的实现类SerialBlob，这个实现类的构造方法需要传一个byte[]数组，所以，我们只用把需要存储的文件转成byte[]数组就可以了</p>
</li>
<li><p>最后，执行sql语句就可以了</p>
</li>
</ol>
<p>这里需要注意的是，要在my.ini服务器配置文件中设置最大存储<br><div class="highlight-box"autocomplete="off" autocorrect="off" autocapitalize="off" spellcheck="false" contenteditable="true"data-rel="PLAIN"><figure class="iseeu highlight /plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br></pre></td><td class="code"><pre><span class="line">//这个大小大于你的存储文件即可</span><br><span class="line">max_allowed_packet=20M</span><br></pre></td></tr></table></figure></div></p>
<p>&emsp;&emsp;[mysqld]下边的是服务器配置，[mysql]下边的是客户端配置</p>
<p>&emsp;&emsp;接下来就是怎么取文件了</p>
<div class="highlight-box"autocomplete="off" autocorrect="off" autocapitalize="off" spellcheck="false" contenteditable="true"data-rel="PLAIN"><figure class="iseeu highlight /plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br></pre></td><td class="code"><pre><span class="line">@Test</span><br><span class="line">    public void test2() throws SQLException, IOException &#123;</span><br><span class="line">        Connection connection = JDBCUtils.getConnection();</span><br><span class="line">        String sql=&quot;SELECT * FROM t_binary WHERE name=?&quot;;</span><br><span class="line">        PreparedStatement pstat = connection.prepareStatement(sql);</span><br><span class="line">        pstat.setString(1,&quot;KenT - 唱给谁听.mp3&quot;);</span><br><span class="line">        ResultSet rs = pstat.executeQuery();</span><br><span class="line">        if (rs.next())&#123;</span><br><span class="line">            Blob blob = rs.getBlob(&quot;data&quot;);</span><br><span class="line">            InputStream in = blob.getBinaryStream();</span><br><span class="line">            FileOutputStream out = new FileOutputStream(&quot;D:/cgst.mp3&quot;);</span><br><span class="line">            IOUtils.copy(in,out);</span><br><span class="line">        &#125;</span><br><span class="line">    &#125;</span><br></pre></td></tr></table></figure></div>
<p>&emsp;&emsp;需要说的就是获取到ResultSet之后，获取到Blob，通过他的getBinaryStream()方法，转成输入流，拿到输入流之后，转成File即可</p>
<h4 id="批处理"><a href="#批处理" class="headerlink" title="批处理"></a>批处理</h4><div class="highlight-box"autocomplete="off" autocorrect="off" autocapitalize="off" spellcheck="false" contenteditable="true"data-rel="PLAIN"><figure class="iseeu highlight /plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br></pre></td><td class="code"><pre><span class="line">@Test</span><br><span class="line">    public void test6() throws SQLException &#123;</span><br><span class="line">        Connection connection = JDBCUtils.getConnection();</span><br><span class="line">        String sql = &quot;INSERT INTO t_user VALUE(?,?,?)&quot;;</span><br><span class="line">        PreparedStatement pstat = connection.prepareStatement(sql);</span><br><span class="line">        for (int i = 0; i &lt; 10000; i++) &#123;</span><br><span class="line">            pstat.setInt(1, i + 1);</span><br><span class="line">            pstat.setString(2, &quot;user&quot; + i);</span><br><span class="line">            pstat.setString(3, i % 2 == 0 ? &quot;男&quot; : &quot;女&quot;);</span><br><span class="line">            pstat.addBatch();</span><br><span class="line">        &#125;</span><br><span class="line">        long start = System.currentTimeMillis();</span><br><span class="line">        pstat.executeBatch();</span><br><span class="line">        long end = System.currentTimeMillis();</span><br><span class="line">        System.out.print(end - start);</span><br><span class="line">    &#125;</span><br></pre></td></tr></table></figure></div>
<p>&emsp;&emsp;注意点：</p>
<ol>
<li>每添加一条数据，调用一遍pstat.addBatch();</li>
<li>当数据添加完以后，调用pstat.executeBatch();执行sql语句</li>
<li>mysql要开启批处理功能，不然慢到你无法想象。在获取Connection传的url后面，添加<code>rewriteBatchedStatements=true</code>。完整url<code>jdbc:mysql://localhost:3306/test4?rewriteBatchedStatements=true</code></li>
</ol>

      
    </div>
    
      <footer class="article-footer">
        完
      </footer>
    
  </div>
  
    
<nav id="article-nav">
  <div class="article-nav-block">
    
      <a href="/2019/06/11/图片滤镜——GPUImage/" id="article-nav-newer" class="article-nav-link-wrap">
        <strong class="article-nav-caption"></strong>
        <div class="article-nav-title">
          
            图片滤镜——GPUImage
          
        </div>
      </a>
    
  </div>
  <div class="article-nav-block">
    
      <a href="/2018/10/11/MySQL数据库操作（五）——多表查询/" id="article-nav-older" class="article-nav-link-wrap">
        <div class="article-nav-title">MySQL数据库操作（五）——多表查询</div>
        <strong class="article-nav-caption"></strong>
      </a>
    
  </div>
</nav>

    
  
  
</article>
</section>
        <aside id="sidebar">
  
    <div class="widget-box">
  <div class="avatar-box avatar-item">
    <img class="avatar" src="/uploads/artistic_image/head.jpg" title="头像来自网络"></img>
    <h3 class="avatar-name">
      
        海晨忆
      
    </h3>
    <p class="avatar-slogan">
      先谋生，再谋爱。人间值得，未来可期。
    </p>
  </div>
</div>


  
    
  <div class="widget-box">
    <h3 class="widget-title">分类</h3>
    <div class="widget">
      <ul class="category-list"><li class="category-list-item"><a class="category-list-link" href="/categories/Android-Socket/">Android -Socket</a></li><li class="category-list-item"><a class="category-list-link" href="/categories/Android-加密算法/">Android -加密算法</a></li><li class="category-list-item"><a class="category-list-link" href="/categories/Android-常用功能/">Android -常用功能</a></li><li class="category-list-item"><a class="category-list-link" href="/categories/Android-框架/">Android -框架</a></li><li class="category-list-item"><a class="category-list-link" href="/categories/Android-源码解析/">Android -源码解析</a></li><li class="category-list-item"><a class="category-list-link" href="/categories/Android-自定义view/">Android -自定义view</a></li><li class="category-list-item"><a class="category-list-link" href="/categories/Android-设计模式/">Android -设计模式</a></li><li class="category-list-item"><a class="category-list-link" href="/categories/JAVA-并发/">JAVA -并发</a></li><li class="category-list-item"><a class="category-list-link" href="/categories/Java-SpringBoot/">Java -SpringBoot</a></li><li class="category-list-item"><a class="category-list-link" href="/categories/Tomcat/">Tomcat</a></li><li class="category-list-item"><a class="category-list-link" href="/categories/kotlin/">kotlin</a></li><li class="category-list-item"><a class="category-list-link" href="/categories/数据库-JDBC/">数据库 -JDBC</a></li><li class="category-list-item"><a class="category-list-link" href="/categories/数据库-MySQL/">数据库 -MySQL</a></li></ul>
    </div>
  </div>


  
    

  
    
  
    
  <div class="widget-box">
    <h3 class="widget-title">归档</h3>
    <div class="widget">
      <ul class="archive-list"><li class="archive-list-item"><a class="archive-list-link" href="/archives/2021/07/">July 2021</a></li><li class="archive-list-item"><a class="archive-list-link" href="/archives/2019/11/">November 2019</a></li><li class="archive-list-item"><a class="archive-list-link" href="/archives/2019/10/">October 2019</a></li><li class="archive-list-item"><a class="archive-list-link" href="/archives/2019/09/">September 2019</a></li><li class="archive-list-item"><a class="archive-list-link" href="/archives/2019/08/">August 2019</a></li><li class="archive-list-item"><a class="archive-list-link" href="/archives/2019/07/">July 2019</a></li><li class="archive-list-item"><a class="archive-list-link" href="/archives/2019/06/">June 2019</a></li><li class="archive-list-item"><a class="archive-list-link" href="/archives/2018/10/">October 2018</a></li><li class="archive-list-item"><a class="archive-list-link" href="/archives/2018/05/">May 2018</a></li><li class="archive-list-item"><a class="archive-list-link" href="/archives/2018/03/">March 2018</a></li><li class="archive-list-item"><a class="archive-list-link" href="/archives/2018/02/">February 2018</a></li></ul>
    </div>
  </div>

  
    
  <div class="widget-box">
    <h3 class="widget-title">最新文章</h3>
    <div class="widget">
      <ul>
        
          <li>
            <a href="/2021/07/27/JAVA—公平锁，非公平锁，悲观锁，乐观锁，死锁/">JAVA—公平锁，非公平锁，悲观锁，乐观锁，死锁</a>
          </li>
        
          <li>
            <a href="/2021/07/19/JAVA—线程同步器AQS/">JAVA—线程同步器AQS</a>
          </li>
        
          <li>
            <a href="/2021/07/07/Android模拟点击/">Android模拟点击</a>
          </li>
        
          <li>
            <a href="/2019/11/27/SpringBoot系列-消息-RabbitMQ-（二十）/">SpringBoot系列-消息(RabbitMQ)（二十）</a>
          </li>
        
          <li>
            <a href="/2019/11/13/SpringBoot系列-Docker（十九）/">SpringBoot系列-Docker（十九）</a>
          </li>
        
      </ul>
    </div>
  </div>

  
      <div class="widget-box">
    <h3 class="widget-title">友情链接</h3>
    <div class="widget">
      
        <a class="hrf" style="display: block;" href="https://github.com/haichenyi" title target='_blank'
        >Github</a>
      
        <a class="hrf" style="display: block;" href="https://www.jianshu.com/u/6077ee440c37" title target='_blank'
        >简书</a>
      
        <a class="hrf" style="display: block;" href="https://blog.csdn.net/qq_27634797" title target='_blank'
        >CSDN</a>
      
    </div>
  </div>

  
</aside>
      </div>
      <footer id="footer">
  <div class="foot-box footers global-width">
    &copy;2017-2021 海晨忆 &nbsp;&nbsp;
    <script async src="//busuanzi.ibruce.info/busuanzi/2.3/busuanzi.pure.mini.js"></script>
    <span id="busuanzi_container_site_pv">阁下是第<span id="busuanzi_value_site_pv"></span>个访客</span>
  </div>
</footer>
      <script src="https://code.jquery.com/jquery-2.0.3.min.js"></script>
<script>
if (!window.jQuery) {
var script = document.createElement('script');
script.src = "/js/jquery-2.0.3.min.js";
document.body.write(script);
}
</script>

  <link rel="stylesheet" href="/fancybox/jquery.fancybox.css">
  <script src="/fancybox/jquery.fancybox.pack.js"></script>


<script src="/js/script.js"></script>



    </div>
    <nav id="mobile-nav" class="mobile-nav-box">
  <div class="mobile-nav-img mobile-nav-top"></div>
  
    <a href="/" class="mobile-nav-link">首页</a>
  
    <a href="/archives" class="mobile-nav-link">归档</a>
  
    <a href="/about" class="mobile-nav-link">简历</a>
  
  <div class="mobile-nav-img  mobile-nav-bottom"></div>
</nav>    
  </div>
</body>
</html>